package com.hd.core.project.module.controller;

import com.baomidou.mybatisplus.mapper.Condition;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hd.core.framework.aspectj.lang.annotation.Log;
import com.hd.core.framework.aspectj.lang.constant.BusinessType;
import com.hd.core.framework.web.domain.AjaxResult;
import com.hd.core.framework.web.page.TableDataInfo;
import com.hd.core.project.module.base.WrapperBaseController;
import com.hd.core.project.module.config.EduModuleProperties;
import com.hd.core.project.module.domain.EduUploadData;
import com.hd.core.project.module.domain.EduUploadDataTitle;
import com.hd.core.project.module.service.EduUploadDataService;
import com.hd.core.project.module.service.EduUploadDataTitleService;
import com.hd.core.project.module.utils.FileDataUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Past;
import java.io.File;
import java.util.*;

/**
 * 上传资料 
 *
 * @author RichardTang
 */
@Controller
@SuppressWarnings("all")
@RequestMapping("/module/edu/upload-data")
public class EduUploadDataController extends WrapperBaseController<EduModuleProperties> {

    @Autowired
    private EduUploadDataService eduUploadDataService;

    @Autowired
    private EduUploadDataTitleService eduUploadDataTitleService;

    EduUploadDataController() {
        super("/upload-data");
    }

    /**
     * @param date 默认日期值
     * @param type 文件类型 0代表查询全部
     * @return
     */
    private Condition selectConditionGenerate(String date, String type){
        Integer year = Integer.parseInt(date.split("-")[0]);
        Integer month = Integer.parseInt(date.split("-")[1]);
        Condition condition = new Condition();
        if(StringUtils.isNoneBlank(type) && !type.equals("0")){
            condition.orderBy("type");
            condition.eq("type",type);
            condition.eq("year",year);
            condition.eq("month",month);
        }
        return condition;
    }

    /**
     * 将已经存到硬盘的资料文件的标题写入到数据库中存储
     * @param diskFileData 要操作的文件对象集合
     */
    @Scope("singleton")
    public synchronized void writerDataBase(List<File> diskFileData){
        Map<String, List> parseResult = FileDataUtils.parseFileData(diskFileData);
        List<EduUploadDataTitle> parseResultOfTeacher = (List<EduUploadDataTitle>)parseResult.get("eduTitle");
        //查询数据库中是否以及有记录了 回现id
        for (EduUploadDataTitle titleObj : parseResultOfTeacher) {
            Integer tempId = eduUploadDataTitleService.queryIdByYeayMonthSheetName(titleObj);
            if (tempId != null)
                titleObj.setId(tempId);
        }
        eduUploadDataService.insertParseAfterData(parseResult);
    }

    /**
     * 上传资料文件(XMLX文件)
     */
    @GetMapping
    @RequiresPermissions("module-edu:upload-data:view")
    public String eduUploadData(){
        return getResponseViewPath("/upload-data");
    }

    /**
     * 查询文件标题
     */
    @GetMapping("/title")
    @RequiresPermissions("module-edu:upload-data:list")
    public ResponseEntity title(String date, String type){
        List<EduUploadDataTitle> result = null;
        if(null == date && date.isEmpty()){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }else{
            Condition condition = selectConditionGenerate(date, type);
            result = eduUploadDataTitleService.selectList(condition);
        }
        if (result != null && result.size() > 0)
            return ResponseEntity.ok(result);
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }

    /**
     * 查询教务科-上传资料列表
     */
    @ResponseBody
    @PostMapping("/list")
    @RequiresPermissions("module-edu:upload-data:list")
    public TableDataInfo list(EduUploadData eduUploadData){
        startPage();
        Map<String, Object> params = eduUploadData.getParams();
        EntityWrapper<EduUploadData> ew = new EntityWrapper<EduUploadData>(eduUploadData);
        if(params != null && !params.isEmpty()){
            String editBeginDate = (String)params.get("editBeginDate");
            String editEndDate = (String)params.get("editEndDate");
            String uploadBeginDate = (String)params.get("uploadBeginDate");
            String uploadEndDate = (String)params.get("uploadEndDate");
            if(!StringUtils.isAnyEmpty(editBeginDate,editEndDate)){
                ew.between("upload_date",uploadBeginDate,uploadEndDate);
            }
            if(!StringUtils.isAnyEmpty(uploadBeginDate,uploadEndDate)){
                ew.between("edit_date",editBeginDate,editEndDate);
            }
        }
        List<EduUploadData> list = eduUploadDataService.selectList(ew);
        return getDataTable(list);
    }

    /**
     * 新增教务科-上传资料
     */
    @GetMapping("/fileupload")
    public String uploadData(){
        return getResponseViewPath("/fileupload");
    }

    /**
     * 保持前台传过来的资料文件
     */
    @ResponseBody
    @PostMapping("/fileupload")
    @RequiresPermissions("module-edu:upload-data:upload-data")
    @Log(title = "教务科-上传资料", action = BusinessType.INSERT)
    public AjaxResult uploadDataSave(@RequestParam("files") MultipartFile[] files){
        boolean result = false;
        try {
            if(files.length > 0){
                Map<String, List> resultMap = FileDataUtils.transferToDiskAll(files, properties, getUser());
                //TODO 这里应该考虑处理断电的情况 2018年8月3日22:55:14
                //记录上传操作
                result = eduUploadDataService.insertBatch(resultMap.get("eduUploadDatas"));
                //TODO 这种写法并不好 后期考虑用线程池来优化
                new Thread(() -> writerDataBase(resultMap.get("diskFileData"))).start();
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return toAjax(result);
    }

    /**
     * 修改教务科-上传资料
     */
    @GetMapping("/edit/{uploadId}")
    public String edit(@PathVariable("uploadId") Integer uploadId, ModelMap mmap){
        EduUploadData eduUploadData = eduUploadDataService.selectById(uploadId);
        mmap.put("eduUploadData", eduUploadData);
        return getResponseViewPath("/edit");
    }

    /**
     * 修改保存教务科-上传资料
     */
    @ResponseBody
    @PostMapping("/edit")
    @RequiresPermissions("module-edu:upload-data:edit")
    @Log(title = "教务科-上传资料", action = BusinessType.UPDATE)
    public AjaxResult editSave(EduUploadData eduUploadData){
        eduUploadData.setEditDate(new Date());
        return toAjax(eduUploadDataService.updateById(eduUploadData));
    }

    /**
     * 删除教务科-上传资料
     */
    @ResponseBody
    @PostMapping( "/remove")
    @RequiresPermissions("module-edu:upload-data:remove")
    @Log(title = "教务科-上传资料", action = BusinessType.DELETE)
    public AjaxResult remove(Integer[] ids){
        List<Integer> integers = Arrays.asList(ids);
        return toAjax(eduUploadDataService.deleteBatchIds(integers));
    }
}

